import path from 'path'
import express from 'express'
import favicon from 'serve-favicon'
import router from './router'
import redis from './redis'
import { get } from '../common/conf'

// 连接本地MongoDB数据库
// import './config/db.js'

export default async app => {
  // redis
  await redis.runRedis()

  // views
  const viewsPathM = [
    ...new Set(
      [
        '/page',
        ...get('path.views')
      ]
    )
  ]

  app.use(express.query())

  // static
  const publicDir = path.join(__dirname, '../../public')
  const staticDir = path.join(__dirname, '../../public/static')
  const viewDir = path.join(__dirname, 'views')
  app.use(express.static(publicDir))
  // uncomment after placing your favicon in /public
  app.use(favicon(path.join(publicDir, 'favicon.ico')))
  // view engine setup
  app.set('views', viewDir)

  // .ejs
  // app.set('view engine', 'ejs')
  // app.engine('html', require('ejs').__express)

  // .html
  app.set('view engine', 'html')
  app.engine('html', require('ejs').__express)

  // .jsx
  // app.set('view engine', 'html')
  // app.engine('html', require('express-react-views').createEngine())

  router(app, redis.getClient())

  // catch 404 and forward to error handler
  app.use((req, res, next) => {
    const err = new Error('Not Found')
    err.status = 404
    err.message = 'Not Found!'
    next(err)
  })

  // error handler and will print stacktrace
  app.use((err, req, res, next) => {
    const {
      path,
      _startTime,
      _remoteAddress
    } = req
    console.log('[errorHandler]', {
      err: err.name,
      path,
      _startTime,
      _remoteAddress
    })
    let message = `${path} could not be found`
    if (err.name === 'UnauthorizedError') message = 'Unauthorized'
    const isView = viewsPathM.some((w) => path.startsWith(w))
    if (isView) {
      res.set({ 'Content-Type': 'text/html' })
      res.status(err.status || 500)
      res.render('error', { message })
    } else {
      res.status(404).send({
        status: err.status,
        message: err.message
      })
    }
  })

  // run server
  const host = process.env.HOST || 'localhost'
  const serverPort = get('server.port')
  app.listen(serverPort, () => {
    console.log(`Express Bingo ==> @ http://${host}:${serverPort}`)
  })
}
